<?php
namespace App\Http\Controllers\Api;

use App\Helper\Utils\TimeUtil;
use App\V3\V3_1\Models\LogOutPackageModel;
use App\V3\V3_1\Models\MaterielContentModel;
use App\V3\V3_1\Models\SellGoodsDetail;
use App\V3\V3_1\Models\TallyModel;
use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\DB;

/**
 * 统计
 * Class StatisticsController
 * @package App\Http\Controllers\Api
 */
class StatisticsController extends BaseController
{
    /**
     * 已销售统计
     * change 在 2021/11/11 16:35 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sell(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id','=',$this->getMainUserId()];
        $condition[] = ['out_status','=',1];
        $condition[] = ['pay_status','=',1];
        $condition[] = ['repeal_status','=',0];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('name','type_name')->get();
//        $modelData['data'] = $tallyModel;
//        $modelData['total_piece'] = SellGoodsDetail::where($condition)
//            ->whereBetween('created_at',$date)
//            ->sum('piece');
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value){
            $totalMoney+=$value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,type_name,materiel_no,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('name','type_name')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     * 销售统计
     * change 在 2021/11/18 15:18 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sellProceed(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id','=',$this->getMainUserId()];
        $condition[] = ['out_status','=',1];
        $condition[] = ['pay_status','=',1];
        $condition[] = ['repeal_status','=',0];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = SellGoodsDetail::select(DB::raw("sum(price*num) as total_price,sell_date"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('sell_date')->get();
        $totalMoney = 0;
        foreach ($tallyModel as $value){
            $totalMoney+=$value['total_price'];
        }
        $SellGoodsDetail = SellGoodsDetail::select(DB::raw("sum(price*num) as total_price,sell_date"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('sell_date')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
        $modelData['total_money'] = round($totalMoney,2);//总销售额

        foreach ($SellGoodsDetail['data'] as &$v){
            $v['sell_date'] = date('Y-m-d',strtotime($v['sell_date']));
        }
        $modelData['data'] = $SellGoodsDetail;
        return $this->success($modelData);
    }
    /**
     * 成本统计
     * change 在 2021/11/11 16:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cost(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }

        $modelData['data'] = LogOutPackageModel::select(DB::raw("sum(num) as num,materiel_img as image,materiel_name as name,type_name,materiel_no,ROUND(sum(price)/count(*),2) price,sum(mean_cost*num) as total_cost_price"))
            ->from('log_out_package as a')
            ->leftJoin('materiel_type as b','a.materiel_type_id', '=','b.id')
            ->where('a.main_id',$this->getMainUserId())
            ->where('a.is_cancel',0)
            ->whereBetween('out_time',$date)
            ->groupBy('name','type_name')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])
            ->toArray();

        $totalMoney = 0;
        $totalNum = 0;
        foreach ($modelData['data']['data'] as &$value){
            $value['price'] = round($value['price'],2);
            $totalMoney+=$value['total_cost_price'];
            $totalNum += $value['num'];
        }
        $modelData['total_money'] = $totalMoney;//总成本
        $modelData['total_num'] = $totalNum;
        return $this->success($modelData);
    }

    /**
     * 进货
     * change 在 2021/11/11 16:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stock(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition[] = ['main_id','=',$this->getMainUserId()];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = MaterielContentModel::select(DB::raw("sum(num) as num,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b','a.materiel_id', '=','b.id')
            ->where('a.main_id',$this->getMainUserId())
            ->where('in_storage_status',2)
            ->whereBetween('a.purchase_time',$date)
            ->groupBy('materiel_name','type_name')->get();
        $totalMoney = 0;
        $totalNum = 0;
        foreach ($tallyModel as $value){
            $totalMoney+=$value['total_price'];
            $totalNum += $value['num'];
        }
        $modelData['data'] = MaterielContentModel::select(DB::raw("sum(num) as num,materiel_img,materiel_name,type_name,materiel_no,sum(unit_price*num) as total_price"))
            ->from('materiel_content as a')
            ->leftJoin('materiel as b','a.materiel_id', '=','b.id')
            ->where('a.main_id',$this->getMainUserId())
            ->where('in_storage_status',2)
            ->whereBetween('a.purchase_time',$date)
            ->groupBy('materiel_name','type_name')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        $modelData['total_num'] = $totalNum;
        $modelData['total_money'] = $totalMoney;//总销售额
        return $this->success($modelData);
    }

    /**
     * 记账
     * change 在 2021/11/11 16:36 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function tally(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>'required|integer',//时间 1-今日 2-本月 3-本季
            'bill_type' =>'integer',//收支类型：0-收入 1-支出'
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $condition['main_id'] = $this->getMainUserId();
        isset($data['bill_type'])?$condition['type'] = $data['bill_type']:'';

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = $this->quarter();
        }
        $tallyModel = TallyModel::select(DB::raw("sum(money) as money,tally_class_name,created_at"))
            ->where($condition)
            ->whereBetween('created_at',$date)
            ->groupBy('tally_class_name','created_at')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
        $modelData['total_money'] = TallyModel::where($condition)
            ->whereBetween('created_at',$date)
            ->sum('money');
        foreach ($tallyModel['data'] as &$v){
            $v['created_at'] = date('Y-m-d',strtotime($v['created_at']));
        }
        $modelData['data'] = $tallyModel;
        return $this->success($modelData);
    }

    /**
     * 当前季度
     * change 在 2021/11/12 10:55 创建
     * @return array
     */
    public function quarter(){
        $moth =  (int)date('m');
        if(in_array($moth,[1,2,3])){
            $startDate = strtotime(date('Y').'-01');
            $endDate = strtotime(date('Y').'-03-31 23:59:59');
        }elseif (in_array($moth,[4,5,6])){
            $startDate = strtotime(date('Y').'-04');
            $endDate = strtotime(date('Y').'-06-30 23:59:59');
        }elseif (in_array($moth,[7,8,9])){
            $startDate = strtotime(date('Y').'-07');
            $endDate = strtotime(date('Y').'-09-30 23:59:59');
        }elseif (in_array($moth,[10,11,12])){
            $startDate = strtotime(date('Y').'-10');
            $endDate = strtotime(date('Y').'-12-31 23:59:59');
        }
        return [$startDate, $endDate];
    }
}

